<template>
  <n-layout class="h-full" bordered>
    <div class="h-full flex flex-col">
      <zip-page-header @on-file-change="fileChangeHandler" />
      <f-divider title-placement="left" title="分隔符" />
      <n-layout has-sider>
        <n-layout-sider content-style="padding: 24px;" bordered>
          <!-- <zip-file-tree :zip-file-info="zipFileInfo" /> -->
          <file-tree
            :file-tree-entries="fileTreeEntries"
            :unknown-as-folder="true"
            :expanded-level="1"
            @on-click-file="handleFileClick"
          />
        </n-layout-sider>
        <n-layout-content content-style="padding: 24px;">
          <zip-file-content />
        </n-layout-content>
      </n-layout>
      <n-layout-footer>复兴路</n-layout-footer>
    </div>
  </n-layout>
</template>

<script setup lang="ts">
import { FileTreeEntries, FileTreeEntry } from '@/typings'
import JSZip from 'jszip'
import { TreeOption, UploadFileInfo } from 'naive-ui'
import { ref, shallowRef } from 'vue'
import { FDivider, FileTree } from '@/components'
import { ZipPageHeader, ZipFileContent } from './components'
import { convertToFileTree, type FileMap } from '@/utils'

const zipFileInfo = ref<UploadFileInfo>()
const fileTreeEntries = shallowRef<FileTreeEntries>(
  // convertToFileTree(['a/bb/ccc', 'a/bb', 'b/c', 'd'])
  convertToFileTree(['a/b', 'a/b/c', 'a/d', 'b/x.json'])
)

function convert(zip: JSZip): FileTreeEntries {
  const fileMap: FileMap = {}
  zip.forEach((relativePath, zipEntry) => {
    fileMap[relativePath] = zipEntry
  })
  return convertToFileTree(fileMap)
}

function fileChangeHandler(fileInfo: UploadFileInfo) {
  const file = fileInfo.file
  if (!file) return
  JSZip.loadAsync(file)
    .then((zip) => {
      fileTreeEntries.value = convert(zip)
    })
    .catch((e) => {
      console.log('文件读取失败')
      console.log('error:', e)
    })
  zipFileInfo.value = fileInfo
}

function handleFileClick(e: TreeOption) {
  console.log('文件信息:', e)
}
</script>

<style scoped></style>
